from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV

# 获取数据集
iris = load_iris()

# 数据基本处理
x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2)

# 特征工程
# 1.实例化一个转化器
transfer = StandardScaler()
# 2.调用fit_transform,转换数据
x_train = transfer.fit_transform(x_train)
x_test = transfer.fit_transform(x_test)

# 机器学习（模型选择，模型训练）
# 1.实例化一个训练模型
estimator=KNeighborsClassifier()

param_grid = {"n_neighbors":[3,5,7,9]}
estimator = GridSearchCV(estimator,param_grid,cv=10,n_jobs=-1)

# 2.模型训练
estimator.fit(x_train,y_train)

# 模型评估
# y_predict=estimator.predict(x_test)
# print("预测结果为：",y_predict==y_test)
# print("预测结果为：",y_predict)

score=estimator.score(x_test,y_test)
print("模型的准确率为：",score)

# 模型的参数
print("模型的最佳参数为：",estimator.best_params_)
print("模型最佳结果为：",estimator.best_score_)
print("模型在交叉验证的结果为：")
for i in estimator.cv_results_:
    print("参数：",i)
    print(estimator.cv_results_[ i])

